package com.ydlclass;
import com.ydlclass.annotation.YrpcApi;
import com.ydlclass.channelHandler.handler.MethodCallHandler;
import com.ydlclass.channelHandler.handler.YrpcResponseEncoder;
import com.ydlclass.config.Configuration;
import com.ydlclass.core.HeartbeatDetector;
import com.ydlclass.discovery.RegistryConfig;
import com.ydlclass.channelHandler.handler.YrpcRequestDecoder;
import com.ydlclass.loadbalancer.LoadBalancer;

import com.ydlclass.transport.message.YrpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import java.util.TreeMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


@Slf4j
public class YrpcBootstrap {
    //YrpcBootstrap 是个单例，我们希望每个应用程序只有一个实例
    private static YrpcBootstrap yrpcBootstrap = new YrpcBootstrap();

    //全局的配置中心
    private Configuration configuration;

    //保存request对象，可以在当前线程中随时获取
    public static final ThreadLocal<YrpcRequest> REQUEST_THREAD_LOCAL = new ThreadLocal<>();

    //连接的缓存
    // 如果使用InetSocketAddress 这样的类做key, 一定要看他有没有重写equals方法和toString方法.
    public final static Map<InetSocketAddress, Channel> CHANNEL_CACHE = new ConcurrentHashMap<>(16);

    public final static TreeMap<Long, Channel> ANSWER_TIME_CHANNEL_CACHE = new TreeMap<>();


    //维护已经发布且暴露的服务列表 key -> interface的全限定名  value -> ServiceConfig
    public final static Map<String,ServiceConfig<?>> SERVERS_LIST = new ConcurrentHashMap<>(16);

    //定义全局的对外挂起的CompletableFuture
    public final static Map<Long, CompletableFuture<Object>> PENDING_REQUEST = new ConcurrentHashMap<>(128);

    private YrpcBootstrap(){
        //构造启动引导程序，需要做一些初始化
        configuration = new Configuration();
    }
    public Configuration getConfiguration() {
        return configuration;
    }


    public static YrpcBootstrap getInstance(){
        return yrpcBootstrap;
    }

    //用来定义当前应用的名字
    public YrpcBootstrap application(String appName){
        configuration.setAppName(appName);
        return this;
    }

    //用来配置一个注册中心
    public YrpcBootstrap registry(RegistryConfig registryConfig){
        //尝试使用 registryConfig获取一个注册中心
        configuration.setRegistryConfig(registryConfig);
        return this;
    }

    //配置负载均衡策略
    public YrpcBootstrap loadBalancer(LoadBalancer loadBalancer){
        configuration.setLoadBalancer(loadBalancer);
        return this;
    }

    /**
     * --------------------------------服务提供方的相关api-------------------------------------------
     */


    /**
     * 发布服务  ----> 将接口实现，注册到服务中心
     * @param service 封装的需要发布的服务
     * @return this 当前实例
     */
    public YrpcBootstrap publish(ServiceConfig<?> service) {
        // 我们抽象了注册中心的概念，使用注册中心的一个实现，完成注册
        configuration.getRegistryConfig().getRegistry().register(service);

        // 1.当服务调用方，通过接口，方法名，具体的方法参数列表发起调用，怎么知道使用哪些
        // (1) new 一个  (2) spring beanFactory.getBean(Class)  (3) 自己维护映射关系
        SERVERS_LIST.put(service.getInterface().getName(),service);
        return this;
    }

    //批量发布
    public YrpcBootstrap publish(List<ServiceConfig<?>> services) {
        for (ServiceConfig<?> service : services) {
            this.publish(service);
        }
        return this;
    }

    // 启动netty服务
    public void start() {
        //1、创建eventloop，老板只负责处理请求，之后会将请求分发至worker
        EventLoopGroup boss = new NioEventLoopGroup(2);
        EventLoopGroup worker = new NioEventLoopGroup(10);

        try {
            //2、需要一个服务器引导程序
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            //3、配置服务器
            serverBootstrap = serverBootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 这里是provider的核心，我们需要添加很多入站和出战的handler
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new LoggingHandler())
                                    .addLast(new YrpcRequestDecoder())
                                    //根据请求进行方法调用
                                    .addLast(new MethodCallHandler())
                                    .addLast(new YrpcResponseEncoder());
                        }
                    });

            //4、绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(configuration.getPort()).sync();


            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                boss.shutdownGracefully().sync();
                worker.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
    /**
     * --------------------------------服务调用方的相关api-------------------------------------------
     */


    public YrpcBootstrap reference(ReferenceConfig<?> reference) {
        // 开启对这个服务的心跳检测
        HeartbeatDetector.detectHeartbeat(reference.getInterface().getName());
        // 在这个方法里我们是否可以拿到相关的配置项--注册中心
        // 配置reference，将来调用get方法时，方便生成代理对象
        // 1.reference需要一个注册中心
        reference.setRegistry(configuration.getRegistryConfig().getRegistry());
        reference.setGroup(this.getConfiguration().getGroup());
        return this;
    }

    /**
     * 配置序列化的方式
     * @param serializeType 序列化的方式
     * @return
     */
    public YrpcBootstrap serialize(String serializeType) {
        configuration.setSerializeType(serializeType);
        if (log.isDebugEnabled()){
            log.debug("我们配置了使用的序列化的方式为{}.",serializeType);
        }
        return this;
    }

    public YrpcBootstrap compress(String compressType) {
        configuration.setCompressType(compressType);
        if (log.isDebugEnabled()){
            log.debug("我们配置了使用的压缩算法为{}.",compressType);
        }
        return this;
    }

    /**
     * 扫描包，进行批量注册
     * @param packageName 包名
     * @return this
     */
    public YrpcBootstrap scan(String packageName) {
        //1.需要通过packageName获得其下的所有的类的权限定名称
        List<String> classNames = getAllClassNames(packageName);
        //2.通过反射获取它的接口，构建具体实现
        List<Class<?>> classes = classNames.stream()
                .map(className -> {
                    try {
                        return Class.forName(className);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }).filter(clazz -> clazz.getAnnotation(YrpcApi.class) != null)
                .collect(Collectors.toList());

        for(Class<?> clazz : classes){
            // 获取它的接口
            Class<?>[] interfaces = clazz.getInterfaces();
            Object instance = null;
            try {
                instance = clazz.getConstructor().newInstance();
            } catch (InstantiationException | NoSuchMethodException | InvocationTargetException |
                     IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            //获取分组信息
            YrpcApi yrpcApi = clazz.getAnnotation(YrpcApi.class);
            String group = yrpcApi.group();


            for (Class<?> anInterface : interfaces){
                ServiceConfig<?> serviceConfig = new ServiceConfig<>();
                serviceConfig.setInterface(anInterface);
                serviceConfig.setRef(instance);
                serviceConfig.setGroup(group);
                if(log.isDebugEnabled()){
                    log.debug("------------------> 已经通过包扫描，将服务{}发布",anInterface);
                }
                // 发布
                publish(serviceConfig);
            }
        }
        return this;
    }

    private List<String> getAllClassNames(String packageName) {
        //1.通过packageName 获得绝对路径
        //com.ydlclass.xxx.yyy -> E://xxx/xww/sss/com/ydlclass/xxx/yyy
        String basePath = packageName.replaceAll("\\.","/");
        URL url = ClassLoader.getSystemClassLoader().getResource(basePath);
        if(url == null){
            throw new RuntimeException("包扫描时，发现路径不存在.");
        }
        String absolutePath = url.getPath();
        try {
            absolutePath = URLDecoder.decode(absolutePath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //
        List<String> classNames = new ArrayList<>();
        classNames = recursionFile(absolutePath,classNames,basePath);
        return classNames;
    }

    private List<String> recursionFile(String absolutePath, List<String> classNames,String basePath) {
        // 获取文件
        File file = new File(absolutePath);
        // 判断文件是否是文件夹
        if(file.isDirectory()){
            // 找到文件夹的所有的文件
            File[] children = file.listFiles(pathname -> pathname.isDirectory() || pathname.getPath().contains(".class"));
            if(children == null || children.length == 0){
                return classNames;
            }
            for (File child: children) {
                if(child.isDirectory()){
                    // 递归调用
                    recursionFile(child.getAbsolutePath(),classNames,basePath);
                }else{
                    // 文件 --> 类的权限定名称
                    String className = getClassNameByAbsolutePath(child.getAbsolutePath(),basePath);
                    classNames.add(className);
                }
            }
        }else{
            String className = getClassNameByAbsolutePath(absolutePath,basePath);
            classNames.add(className);
        }
        return classNames;
    }

    private String getClassNameByAbsolutePath(String absolutePath,String basePath) {
        // D:\IDEA\IDEA code\RPC-zzk\yrpc-framwork\yrpc-core\target\classes\com\ydlclass\channelHandler\ConsumerChannelInitializer.class
        // com\ydlclass\channelHandler\ConsumerChannelInitializer.class ---> com.ydlclass.channelHandler.ConsumerChannelInitializer
        String fileName = absolutePath.substring(absolutePath.indexOf(basePath.replaceAll("/","\\\\")))
                .replaceAll("\\\\","\\.");

        fileName = fileName.substring(0,fileName.indexOf(".class"));

        return fileName;
    }

    public YrpcBootstrap group(String group) {
        this.getConfiguration().setGroup(group);
        return this;
    }
}


